import { Button, Dropdown } from "antd";
import { Link, useMatches } from "react-router";
import { useAtomValue, useSetAtom } from "jotai";
import useTime from "@/lib/hooks/useTime";
import { isAdminAtom, logoutAtom } from "@/store/user";
import Logo from "@/assets/images/logo.png?jsx";
import GearIcon from "@/assets/icons/gear.svg?jsx";

import { setHeaderAtom, headerAtom } from "@/store/header";
import clsm from "@/lib/utils/clsm";
import useOnUpdated from "@/lib/hooks/useOnUpdated";
import Alarms from "./Alarms";

export default function Header() {
  const time = useTime();
  const isAdmin = useAtomValue(isAdminAtom);
  const header = useAtomValue(headerAtom);
  const setHeader = useSetAtom(setHeaderAtom);
  const logout = useSetAtom(logoutAtom);

  const mathces = useMatches();
  useOnUpdated(() => {
    let title = "";
    for (let i = mathces.length - 1; i >= 0; i--) {
      title = (mathces[i].handle as any)?.title;
      if (title) {
        break;
      }
    }
    setHeader({
      title,
      style: {},
      pulse: false,
    });
  }, [mathces]);

  return (
    <header className="relative flex h-12 items-center gap-x-8 px-6 dark:bg-black">
      <Link to="/" className="size-9 overflow-hidden rounded-full bg-sky-500">
        <Logo />
      </Link>
      <div className="ml-auto flex h-full items-center gap-x-4">
        <Alarms />
        <div>{time}</div>
        <Dropdown
          menu={{
            items: [{ key: "logout", label: "退出登录", onClick: logout }],
          }}
          trigger={["click"]}
          placement="bottom"
        >
          <Button className="text-base" type="text">
            {isAdmin ? "管理员" : "操作员"}
          </Button>
        </Dropdown>
      </div>
      <Link to="/setting">
        <GearIcon />
      </Link>
      <div
        className={clsm(
          "absolute left-1/2 -translate-x-1/2 text-lg font-bold",
          header.pulse && "animate-pulse",
        )}
        style={header.style}
      >
        {header.title}
      </div>
    </header>
  );
}
